﻿using Furion;
using Furion.DatabaseAccessor;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.Core;
using Furion.Core.Entities.Enums;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Security.Claims;
using Furion.DatabaseAccessor.Extensions;
using System.Drawing;
using Furion.DistributedIDGenerator;
using Microsoft.Extensions.Caching.Memory;

namespace Furion.Application
{

    [AppAuthorize, ApiDescriptionSettings("System", Name = "Permission", Order = 3, Tag = "权限")]
    public class PermissionService : IDynamicApiController
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IRepository<Permission> _permissionRepository;
        private readonly IRepository<User> _userRepository;

        private readonly IAuthorizationManager _authorizationManager;

        /// <summary>
        /// 缓存
        /// </summary>
        private readonly IMemoryCache _memoryCache;

        public PermissionService(IHttpContextAccessor httpContextAccessor,
            IRepository<Permission> permissionRepository,
            IRepository<User> useRepository,
            IAuthorizationManager authorizationManager,
            IMemoryCache memoryCache)
        {
            _httpContextAccessor = httpContextAccessor;
            _permissionRepository = permissionRepository;
            _userRepository = useRepository;
            _authorizationManager = authorizationManager;
            _memoryCache = memoryCache;
        }


        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine(ConstPermission.Permission_Add),HttpPost("/Permission/Add"), ApiDescriptionSettings(Name = "Add")]
        public async Task AddAsync([Required] PermissionAddInput input)
        {
            var addInput = input.Adapt<Permission>();
            addInput.CreatedTime = DateTime.Now;
            addInput.UpdatedTime = DateTime.Now;
            addInput.CreatedUserId = _authorizationManager.UserId;
            var entryEntity = await _permissionRepository.InsertNowAsync(addInput);
        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine(ConstPermission.Permission_Edit),HttpPost("/Permission/Edit"), ApiDescriptionSettings(Name = "Edit")]
        public async Task EditAsync([Required] PermissionEditInput input)
        {
            var editInput = input.Adapt<Permission>();
            editInput.UpdatedTime = DateTime.Now;
            editInput.UpdatedUserId = _authorizationManager.UserId;
            await _permissionRepository.UpdateAsync(editInput);
        }


        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine(ConstPermission.Permission_List), HttpGet("/Permission/PageList"), ApiDescriptionSettings(Name = "PageList")]
        public async Task<PagedList<Permission>> PageListAsync([FromQuery] PermissionSearchPageInput input)
        {
            var hasKeyword = !string.IsNullOrEmpty(input.Keyword?.Trim());

            var list = await _permissionRepository.DetachedEntities
                .Where(input.Sort>0,a=>a.Sort==input.Sort)
                .Where(hasKeyword, a => a.PermissionName.Contains(input.Keyword.Trim()) || a.PermissionCode.Contains(input.Keyword.Trim()) )
                .OrderBy(a => a.Id)
                .ToPagedListAsync(input.PageIndex, input.PageSize);
            return list;
        }


        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine(ConstPermission.Permission_List), HttpGet("/Permission/List"), ApiDescriptionSettings(Name = "List")]
        public async Task<List<Permission>> ListAsync([FromQuery] PermissionSearchInput input)
        {
            var hasKeyword = !string.IsNullOrEmpty(input.Keyword?.Trim());

            var list = await _permissionRepository.DetachedEntities
                .Where(hasKeyword, a => a.PermissionName.Contains(input.Keyword.Trim()) || a.PermissionCode.Contains(input.Keyword.Trim()))
                .OrderByDescending(a => a.UpdatedTime)
                .ToListAsync();
            return list;
        }


        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine(ConstPermission.Permission_Delete),HttpPost("/Permission/Delete"), ApiDescriptionSettings(Name = "Delete")]
        public async Task DeleteRange(PermissionDeleteRangeInput input)
        {
            var items = await _permissionRepository.DetachedEntities.Where(u => input.Ids.Contains(u.Id)).ToListAsync();
            if(items.Count>0)
            {
                await _permissionRepository.DeleteNowAsync(items);
            }
            
        }


    }
}
